package com.che.software.testato.business;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.che.software.testato.business.exception.ActionSearchManagerException;
import com.che.software.testato.business.exception.HierarchyCreationManagerException;
import com.che.software.testato.business.exception.HierarchySearchManagerException;
import com.che.software.testato.business.exception.ItemSearchManagerException;
import com.che.software.testato.business.exception.ProjectSearchManagerException;
import com.che.software.testato.business.exception.VariantSearchManagerException;
import com.che.software.testato.business.exception.VersionSearchManagerException;
import com.che.software.testato.domain.dao.IActionDAO;
import com.che.software.testato.domain.dao.IHierarchyDAO;
import com.che.software.testato.domain.dao.IItemDAO;
import com.che.software.testato.domain.dao.IProjectDAO;
import com.che.software.testato.domain.dao.IVariantDAO;
import com.che.software.testato.domain.dao.IVersionDAO;
import com.che.software.testato.domain.dao.jdbc.exception.ActionSearchDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.HierarchyCreationDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.HierarchySearchDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.ItemSearchDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.ProjectSearchDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.VariantSearchDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.VersionSearchDAOException;
import com.che.software.testato.domain.entity.Action;
import com.che.software.testato.domain.entity.Hierarchy;
import com.che.software.testato.domain.entity.Item;
import com.che.software.testato.domain.entity.Version;
import com.che.software.testato.domain.entity.creation.HierarchyCreation;
import com.che.software.testato.domain.entity.search.ActionSearch;
import com.che.software.testato.domain.entity.search.HierarchySearch;
import com.che.software.testato.domain.entity.search.ItemSearch;
import com.che.software.testato.domain.entity.search.ProjectSearch;
import com.che.software.testato.domain.entity.search.VersionSearch;

/**
 * Manager dedicated to the hierarchies.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @since July, 2011.
 * 
 *        This file is part of Testato.
 * 
 *        Testato is free software: you can redistribute it and/or modify it
 *        under the terms of the GNU General Public License as published by the
 *        Free Software Foundation, either version 3 of the License, or (at your
 *        option) any later version.
 * 
 *        Testato is distributed in the hope that it will be useful, but WITHOUT
 *        ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *        FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *        for more details.
 * 
 *        You should have received a copy of the GNU General Public License
 *        along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 *        Testato's logo is a creation of Arrioch
 *        (http://arrioch.deviantart.com/) and it's distributed under the terms
 *        of the Creative Commons License.
 */
@Service("hierarchyManager")
public class HierarchyManager {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(HierarchyManager.class);

	/**
	 * Members.
	 */
	@Autowired
	private IActionDAO actionDAO;
	@Autowired
	private IHierarchyDAO hierarchyDAO;
	@Autowired
	private IItemDAO itemDAO;
	@Autowired
	private IProjectDAO projectDAO;
	@Autowired
	private IVariantDAO variantDAO;
	@Autowired
	private IVersionDAO versionDAO;

	/**
	 * Creates a hierarchy from a bean of criterions.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param creationBean the bean of criterions.
	 * @since July, 2011.
	 * @throws HierarchyCreationManagerException if an error occurs during the
	 *         creation.
	 */
	public void createHierarchyFromBean(HierarchyCreation creationBean) throws HierarchyCreationManagerException {
		LOGGER.debug("createHierarchyFromBean().");
		try {
			hierarchyDAO.createHierarchyFromBean(creationBean);
		} catch (HierarchyCreationDAOException e) {
			throw new HierarchyCreationManagerException(e);
		}
	}

	/**
	 * Checks if a hierarchy is already existing for a given version id.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param versionId the version id to check
	 * @return true if a hierarchy is already existing, else false.
	 * @since July, 2011.
	 * @throws HierarchySearchManagerException if an error occurs during the
	 *         search.
	 */
	public boolean isHierarchyExistingFromVersionId(int versionId) throws HierarchySearchManagerException {
		LOGGER.debug("isHierarchyExistingFromVersionId(" + versionId + ").");
		try {
			return hierarchyDAO.isHierarchyExistingFromVersionId(versionId);
		} catch (HierarchySearchDAOException e) {
			throw new HierarchySearchManagerException(e);
		}
	}

	/**
	 * Hierarchy search from a bean of criterions.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param searchBean the criterions to use for the search.
	 * @return the resulting object list.
	 * @since July, 2011.
	 * @throws HierarchySearchManagerException if an error occurs during the
	 *         search.
	 */
	public List<Hierarchy> searchHierarchy(HierarchySearch searchBean) throws HierarchySearchManagerException {
		LOGGER.debug("searchHierarchy().");
		try {
			return hierarchyDAO.searchHierarchy(searchBean);
		} catch (HierarchySearchDAOException e) {
			throw new HierarchySearchManagerException(e);
		}
	}

	/**
	 * Eligibles to elicitation hierarchies search.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @return the resulting object list.
	 * @since July, 2011.
	 * @throws ActionSearchManagerException if an error occurs during an action
	 *         search.
	 * @throws HierarchySearchManagerException if an error occurs during the
	 *         search.
	 * @throws ItemSearchManagerException if an error occurs during an item
	 *         search.
	 * @throws VariantSearchManagerException if an error occurs during a variant
	 *         search.
	 * @throws VersionSearchManagerException if an error occurs during a version
	 *         search.
	 * @throws ProjectSearchManagerException if an error occurs during a project
	 *         search.
	 */
	public List<Hierarchy> searchEligiblesHierarchies() throws ActionSearchManagerException, HierarchySearchManagerException, ItemSearchManagerException, VariantSearchManagerException, VersionSearchManagerException, ProjectSearchManagerException {
		LOGGER.debug("searchEligiblesHierarchies().");
		try {
			List<Hierarchy> result = new ArrayList<Hierarchy>();
			for (Hierarchy hierarchy : hierarchyDAO.searchHierarchy(new HierarchySearch())) {
				if (isEligible(hierarchy.getActionPlanId())) {
					Version version = versionDAO.searchVersion(new VersionSearch(hierarchy.getVersionId())).get(0);
					hierarchy.setVersion(version);
					hierarchy.setProject(projectDAO.searchProject(new ProjectSearch(version.getProjectId())).get(0));
					result.add(hierarchy);
				}
			}
			return result;
		} catch (HierarchySearchDAOException e) {
			throw new HierarchySearchManagerException(e);
		} catch (ActionSearchDAOException e) {
			throw new ActionSearchManagerException(e);
		} catch (ItemSearchDAOException e) {
			throw new ItemSearchManagerException(e);
		} catch (VariantSearchDAOException e) {
			throw new VariantSearchManagerException(e);
		} catch (VersionSearchDAOException e) {
			throw new VersionSearchManagerException(e);
		} catch (ProjectSearchDAOException e) {
			throw new ProjectSearchManagerException(e);
		}
	}

	/**
	 * Recursive method. Checks if the level represented by the given action
	 * plan id is eligible to scripts elicitation. In other words, checks if
	 * every item is operationnalized (with variants generated) or refined with
	 * a lower level eligible to elicitation.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param actionPlanId
	 * @return true if the level is eligible to scripts elicitation, else false.
	 * @throws ActionSearchDAOException if an error occurs during an action
	 *         search.
	 * @throws ItemSearchDAOException if an error occurs during an item search.
	 * @throws VariantSearchDAOException if an error occurs during a variant
	 *         search.
	 * @since July, 2011.
	 */
	private boolean isEligible(int actionPlanId) throws ActionSearchDAOException, ItemSearchDAOException, VariantSearchDAOException {
		LOGGER.debug("isEligible(" + actionPlanId + ").");
		List<Action> actions = actionDAO.searchAction(new ActionSearch(actionPlanId));
		for (Action action : actions) {
			ItemSearch searchBean = new ItemSearch();
			searchBean.setParentAction(action.getActionId());
			for (Item item : itemDAO.searchItem(searchBean)) {
				if (0 == item.getActionPlanId() && 0 == item.getTestCaseId()) {
					LOGGER.debug("Stop condition: not defined item: " + item.getLabel() + ".");
					return false; // 1st stop condition.
				}
				if (0 != item.getTestCaseId() && !variantDAO.areVariantsExistingFromTestCaseId(item.getTestCaseId())) {
					LOGGER.debug("Stop condition: not generated variants: " + item.getLabel() + ".");
					return false; // 2nd stop condition.
				}
				if (0 != item.getActionPlanId()) {
					return isEligible(item.getActionPlanId()); // Recursive
																// call.
				}
			}
		}
		return (actions != null && !actions.isEmpty());
	}

	/**
	 * Getter for the private field value hierarchyDAO.
	 * 
	 * @return the hierarchyDAO field value.
	 */
	public IHierarchyDAO getHierarchyDAO() {
		return hierarchyDAO;
	}

	/**
	 * Setting a value to the hierarchyDAO field.
	 * 
	 * @param hierarchyDAO the value to set.
	 */
	public void setHierarchyDAO(IHierarchyDAO hierarchyDAO) {
		this.hierarchyDAO = hierarchyDAO;
	}

	/**
	 * Getter for the private field value actionDAO.
	 * 
	 * @return the actionDAO field value.
	 */
	public IActionDAO getActionDAO() {
		return actionDAO;
	}

	/**
	 * Setting a value to the actionDAO field.
	 * 
	 * @param actionDAO the value to set.
	 */
	public void setActionDAO(IActionDAO actionDAO) {
		this.actionDAO = actionDAO;
	}

	/**
	 * Getter for the private field value itemDAO.
	 * 
	 * @return the itemDAO field value.
	 */
	public IItemDAO getItemDAO() {
		return itemDAO;
	}

	/**
	 * Setting a value to the itemDAO field.
	 * 
	 * @param itemDAO the value to set.
	 */
	public void setItemDAO(IItemDAO itemDAO) {
		this.itemDAO = itemDAO;
	}

	/**
	 * Getter for the private field value variantDAO.
	 * 
	 * @return the variantDAO field value.
	 */
	public IVariantDAO getVariantDAO() {
		return variantDAO;
	}

	/**
	 * Setting a value to the variantDAO field.
	 * 
	 * @param variantDAO the value to set.
	 */
	public void setVariantDAO(IVariantDAO variantDAO) {
		this.variantDAO = variantDAO;
	}

	/**
	 * Getter for the private field value projectDAO.
	 * 
	 * @return the projectDAO field value.
	 */
	public IProjectDAO getProjectDAO() {
		return projectDAO;
	}

	/**
	 * Setting a value to the projectDAO field.
	 * 
	 * @param projectDAO the value to set.
	 */
	public void setProjectDAO(IProjectDAO projectDAO) {
		this.projectDAO = projectDAO;
	}

	/**
	 * Getter for the private field value versionDAO.
	 * 
	 * @return the versionDAO field value.
	 */
	public IVersionDAO getVersionDAO() {
		return versionDAO;
	}

	/**
	 * Setting a value to the versionDAO field.
	 * 
	 * @param versionDAO the value to set.
	 */
	public void setVersionDAO(IVersionDAO versionDAO) {
		this.versionDAO = versionDAO;
	}

}